package com.xuecheng.learning.config;

import com.xuecheng.base.constant.RabbitMQConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
public class ErrorMessageConfig {

    /**
     * 创建死信交换机
     *
     * @return DirectExchange
     */
    @Bean
    public DirectExchange errorMessageExchange() {
        return new DirectExchange(RabbitMQConstant.EXCHANGE_ERROR_DIRECT, true, false);
    }

    /**
     * 创建死信队列
     *
     * @return Queue
     */
    @Bean
    public Queue errorQueue() {
        return new Queue(RabbitMQConstant.QUEUE_ERROR, true);
    }

    /**
     * 绑定死信队列到死信交换机
     *
     * @param errorQueue               死信队列
     * @param errorMessageExchange 死信交换机
     * @return Binding
     */
    @Bean
    public Binding errorBinding(Queue errorQueue, DirectExchange errorMessageExchange) {
        return BindingBuilder
                .bind(errorQueue)
                .to(errorMessageExchange)
                .with(RabbitMQConstant.ROUTING_KEY_ERROR_DIRECT);
    }

    /**
     * 创建消息恢复者，当消息重试达到最大次数后，将消息转发到指定的交换机（这里是死信交换机）
     *
     * @param rabbitTemplate rabbitTemplate发送消息
     * @return MessageRecoverer
     */
    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate) {
        return new RepublishMessageRecoverer(rabbitTemplate, RabbitMQConstant.EXCHANGE_ERROR_DIRECT, RabbitMQConstant.ROUTING_KEY_ERROR_DIRECT);
    }
}